package main

import (
	"encoding/json"
	"fmt"
	"github.com/gofiber/fiber/v3"
	"github.com/gofiber/fiber/v3/log"
	"github.com/gofiber/fiber/v3/middleware/static"
	"my-fiber/middleware"
)

func main() {
	MiddlewareAndNext()
}

func BasicRouting() {
	app := fiber.New()

	// GET /api/register
	app.Get("/api/*", func(c fiber.Ctx) error {
		msg := fmt.Sprintf("Hello %s", c.Params("*"))
		return c.SendString(msg)
	})

	// GET /flights/LAX-SFO
	app.Get("/flights/:from-:to", func(c fiber.Ctx) error {
		msg := fmt.Sprintf("💸 From: %s, To: %s", c.Params("from"), c.Params("to"))
		return c.SendString(msg) // => 💸 From: LAX, To: SFO
	})

	// GET /dictionary.txt
	app.Get("/:file.:ext", func(c fiber.Ctx) error {
		msg := fmt.Sprintf("📃 %s.%s", c.Params("file"), c.Params("ext"))
		return c.SendString(msg) // => 📃 dictionary.txt
	})

	// GET /john/75
	app.Get("/:name/:age/:gender?", func(c fiber.Ctx) error {
		msg := fmt.Sprintf("👴 %s is %s years old", c.Params("name"), c.Params("age"))
		return c.SendString(msg) // => 👴 john is 75 years old
	})

	// GET /john
	app.Get("/:name", func(c fiber.Ctx) error {
		msg := fmt.Sprintf("Hello, %s 👋!", c.Params("name"))
		return c.SendString(msg) // => Hello john 👋!
	})

	log.Fatal(app.Listen(":3000"))
}

func RouteNaming() {
	app := fiber.New()

	app.Get("/api/*", func(c fiber.Ctx) error {
		msg := fmt.Sprintf("✋ %s", c.Params("*"))
		return c.SendString(msg) // => ✋ register
	}).Name("api")

	route := app.GetRoute("api")

	data, _ := json.MarshalIndent(route, "", "  ")
	fmt.Println(string(data))
	// Prints:
	// {
	//    "method": "GET",
	//    "name": "api",
	//    "path": "/api/*",
	//    "params": [
	//      "*1"
	//    ]
	// }

	log.Fatal(app.Listen(":3000"))
}

func ServingStaticFiles() {
	app := fiber.New()

	// Serve static files from the "./public" directory
	app.Get("/*", static.New("./public"))
	// => http://localhost:3000/js/script.js
	// => http://localhost:3000/css/style.css

	app.Get("/prefix*", static.New("./public"))
	// => http://localhost:3000/prefix/js/script.js
	// => http://localhost:3000/prefix/css/style.css

	// Serve a single file for any unmatched routes
	app.Get("*", static.New("./public/index.html"))
	// => http://localhost:3000/any/path/shows/index.html

	log.Fatal(app.Listen(":3000"))
}

func MiddlewareAndNext() {
	app := fiber.New()
	// Middleware that matches any route
	//app.Use(middleware.Logger(func() {
	//	fmt.Println("Global Filter")
	//}))
	// Middleware that matches all routes starting with /api
	//app.Use("/api", middleware.Logger(func() {
	//	fmt.Println("🥈 Second Filter")
	//}))

	// GET /api/list
	app.Get("/api/list", func(c fiber.Ctx) error {
		fmt.Println("🥉 Last handler")
		return c.SendString("Hello, World list 👋!")
	}, middleware.Logger("get:/api/list"))
	app.Get("/api/lost", func(c fiber.Ctx) error {
		fmt.Println("🥉 Last handler")
		return c.SendString("Hello, World lost👋!")
	}, middleware.Logger("get:/api/lost"))
	log.Fatal(app.Listen(":3000"))
}
